<template>
	<view class="layout">
		<view class="goBack" @click="goBack" :style="{top:(getStatusBarHeight()-2)+'px'}">
			<uni-icons type="back" color="#fff" size="20"></uni-icons>
		</view>
		<!-- <score-view :score="score"></score-view> -->
		<view class="content">
			<view class="title">
				<view class="bg">
					<image src="../../static/bg_title.png" mode="aspectFill"></image>
					<image class="wallet" src="../../static/ic_wallet.png" v-if="false" mode="aspectFill"></image>
				</view>
				<view class="info" :style="{top:20+'px'}">
					<view class="title1">
						{{itemDetail.name + "卡"}}
					</view>
					<view class="title2">
						赶快来刮一下吧
					</view>

				</view>
			</view>

			<view class="usernums" :style="{ height : numHeight + 'rpx'}">
				<view class="items">
					<view class="item" v-for="item in userNums"
						:style="{ border: item.isWin && isShowWin ? '2px solid red' : 'none' }">
						<view class="winnum">
							{{currentText}}
						</view>
					</view>
				</view>
				<canvas v-if="!isShowWin" class="canvas2" id="canvas2" canvas-id="canvas2" @touchstart="touchstart2"
					@touchmove="touchmove2" @touchend="touchend2"></canvas>
			</view>
			<view class="footer">
			</view>
		</view>
	</view>

	<uni-popup ref="resultPopup" :is-mask-click="false" mask-background-color="rgba(0,0,0,0.8)">
		<view class="resultPopup">
			<view class="bg win" v-if="winMoney !== 0">
				<view class="text">祝您-{{currentText}}</view>
			</view>
			<view class="bg loser" v-else>
				<view class="text">{{'再来一次'}}</view>
			</view>
			<view class="submitBtn" @click="onSubmit">
				<button type="primary">再来一次</button>
			</view>

			<view class="close" @click="closeResult">
				<uni-icons type="close" color="#eee" size="40"></uni-icons>
			</view>
		</view>
	</uni-popup>

</template>
<script>
    import { getStatusBarHeight, getNavBarHeight, rpxToPx, pxToRpx } from "@/utils/system.js";
    import { onLoad, onShow, onReady } from "@dcloudio/uni-app";
    import { onMounted, getCurrentInstance } from 'vue';
    import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
    import { getUserScore, SignInGetScore, addUserScore } from "../../utils/common";

    export default {
        data() {
            return {
                title: '',
                titleHeight: 0,
                numHeight: 0,
                isShowWin: false,
                openNums: [],
                userNums: [],
                viewWidth: 0,
                viewHeight: 0,
                score: 0,
                ctx: null,
                viewWidth2: 0,
                viewHeight2: 0,
                ctx2: null,
                points: [],
                points2: [],
                winPoints: 0,
                userPoints: 0,
                resultPopup: null,
                winMoney: 0,
                itemNums: 0,
                currentText: '平安喜乐',
                itemDetail: {}
            };
        },
        onLoad: function (e) {
            this.itemDetail = JSON.parse(e.itemDetail);
            this.title = e.title;
            this.titleHeight = getStatusBarHeight() + 10;
            console.log(uni.getSystemInfoSync().screenHeight + ',' + uni.getSystemInfoSync().pixelRatio);

            this.numHeight = pxToRpx(uni.getSystemInfoSync().screenHeight - getNavBarHeight()) - (350 + 20);

            this.itemNums = 1;
            this.creatNums();
        },
        onShow: function () {
            this.score = getUserScore();
        },
        onMounted: function () {
            this.drawInit2();
        },
        methods: {
            goBack: function () {
                // drawInit();
                uni.navigateBack({
                    success: function () { },
                    fail: function () {
                        uni.reLaunch({
                            url: '/pages/index/shouye'
                        });
                    }
                });
            },
            closeResult: function () {
                this.resultPopup.close();
            },
            onSubmit: function () {
                // if (this.score >= 50) {
                // 	const myScore = addUserScore(-50);
                // 	score.value = myScore;
                this.resultPopup.close();
                this.winMoney = 0;
                // creatNums();
                // drawInit2();

                this.isShowWin = false;

                this.ctx = null;
                this.points = [];
                this.ctx2 = null;
                this.points2 = [];
                this.winPoints = 0;
                this.userPoints = 0;
                setTimeout(() => {
                    this.creatNums();
                    this.drawInit2();
                }, 500);
            },
            creatNums: function () {
                let list = [];
                if (this.itemDetail.winNum) {
                    list = this.itemDetail.winNum;
                } else {
                    list = ["平安喜乐", "皆大欢喜", "喜气洋洋", "国泰民安", "万事如意", "一帆风顺", "平安喜乐", "安居乐业", "吉祥如意", "平安健康", "四海升平"];
                }
                const randomIndex = this.getRandomNum(10);
                console.log('randomIndex:' + randomIndex);
                const random = this.getRandomNum(100);
                this.currentText = list[randomIndex];
                const item = {
                    num: list[randomIndex],
                    money: 100,
                    isWin: true
                };
                this.userNums.push(item);
                this.winMoney = 100;
            },
            getRandomNum: function (num) {
                return Math.floor(Math.random() * num) + 1;
            },
            touchstart2: function (e) {
                let startX = e.changedTouches[0].x;
                let startY = e.changedTouches[0].y;
                let startPoint = {
                    x: startX,
                    y: startY
                };
                // 存点 一起画
                this.points2.push(startPoint);
                // 每次触摸开始，开启新的路径F
                this.ctx2.beginPath();
            },
            touchmove2: function (e) {
                // innerAudioContext.pause()
                let moveX = e.changedTouches[0].x;
                let moveY = e.changedTouches[0].y;
                let movePoint = {
                    x: moveX,
                    y: moveY,
                };
                this.points2.push(movePoint);
                this.userPoints += 1;
                if (this.points2.length >= 2) {
                    this.drawLine2();
                }
                innerAudioContext.play();
                // if(!requestStatus){
                // 	requestStatus = true;

                // 	setTimeout(()=>{
                // 		// 模拟执行完毕
                // 		// 改变 requestStatus
                // 		requestStatus = false;
                // 	}, 100);
                // }
            },
            touchend2: function (e) {
                this.points2 = [];
                this.chechShowAnwser();
            },
            chechShowAnwser: function () {
                console.log(this.winPoints + ',' + this.userPoints);
                if (this.userPoints >= 50) {
                    this.isShowWin = true;
                    setTimeout(() => {
                        if (this.winMoney!= 0) {
                            const innerAudioContext = uni.createInnerAudioContext();
                            innerAudioContext.autoplay = false;
                            innerAudioContext.src = "/static/audio/huanhu.mp3";
                            innerAudioContext.play();
                        } else {
                            const innerAudioContext = uni.createInnerAudioContext();
                            innerAudioContext.autoplay = false;
                            innerAudioContext.src = "/static/audio/kexi.mp3";
                            innerAudioContext.play();
                        }
                        this.resultPopup.open();
                        this.score = addUserScore(this.winMoney);
                    }, 500);
                } else {
                    this.isShowWin = false;
                }
            },
            getViewHW2: function () {
                let info = uni.createSelectorQuery().in(this.$vm).select(".usernums");
                console.log("info: ", info);
                return new Promise((resolve, reject) => {
                    info.boundingClientRect((data) => {
                        console.log("data: " + JSON.stringify(data));
                        this.viewWidth2 = data.width;
                        this.viewHeight2 = data.height;
                        resolve();
                    }).exec(function (res) {
                        // 注意：exec方法必须执行，即便什么也不做，否则不会获取到任何数据
                    });
                });
            },
            drawLine2: function () {
                let point1 = this.points2[0];
                let point2 = this.points2[1];
                this.points2.shift();
                this.ctx2.moveTo(point1.x, point1.y);
                this.ctx2.lineTo(point2.x, point2.y);
                this.ctx2.stroke();
                this.ctx2.draw(true);
            },
            drawInit2: async function () {
                await this.getViewHW2();
                this.ctx2 = uni.createCanvasContext('canvas2');
                let x = this.viewWidth2;
                let y = this.viewHeight2;
                // let x = 400
                // let y = 400
                console.log(x, y);
                // 设置 globalCompositeOperation 为 "dissolve"
                // ctx.value.setGlobalCompositeOperation("dissolve");
                this.ctx2.setFillStyle('#bbb');
                this.ctx2.fillRect(0, 0, x, y);

                this.ctx2.setFontSize(30);
                this.ctx2.setTextBaseline('middle');
                this.ctx2.setFillStyle('black');
                this.ctx2.setTextAlign('center');
                this.ctx2.fillText(this.title, x / 2, y / 2);
                // let image = uni.createSelectorQuery().in(instance).select(".wallet");
                // ctx2.value.drawImage(image,100,100);

                this.ctx2.lineWidth = 4;
                this.ctx2.lineCap = "round";
                this.ctx2.lineJoin = "round";
                this.ctx2.draw(true);
                // 接下来线的样式
                this.ctx2.lineWidth = 80; // 刮的大小
                this.ctx2.lineCap = "round";
                this.ctx2.lineJoin = "round";
                this.ctx2.globalCompositeOperation = 'destination-out'; // 关键是这个属性
            }
        }
    };
</script>

// <!-- // scss 语言类型  scoped css样式的类名仅限当前页面 不污染其它页面 -->
<style lang="scss">
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}

	.layout {
		width: 100%;
		height: 100vh;
		background-color: #008B8B;
		position: relative;

		.goBack {
			position: fixed;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
		}




		.content {
			// width: 100%;
			height: calc(100vh - 40rpx);
			background-color: #de3018;
			margin-top: 0rpx;
			border: 20rpx solid #008B8B;
			box-sizing: content-box;
			border-radius: 20px;
			overflow: hidden;
			position: relative;
			display: flex;
			align-items: center;
			flex-direction: column;

			.title {
				position: relative;
				width: 100%;

				.bg {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 350rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.info {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 350rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;

					.title1 {
						top: 100rpx;
						width: 100%;
						font-size: 110rpx;
						font-weight: bold;
						text-align: center;
						color: #008B8B;
						// color: white;
					}

					.title2 {
						width: 80%;
						font-size: 18px;
						text-align: center;
						color: #de3018;
						background-color: #ffe21d;
						padding: 0 20rpx;
					}

					.title3 {
						width: 100%;
						margin-top: 20rpx;
						font-size: 14px;
						text-align: center;
						color: #ffe21d;
						padding: 0 20rpx;
					}
				}
			}

			.usernums {
				margin-top: 420rpx;
				position: relative;
				width: 95%;
				background-color: #d8d7d7;
				border: 10rpx solid #008B8B;

				.items {
					width: 100%;
					height: 100%;

					.item {
						width: 100%;
						height: 100%;
						// background-color: red;
						display: flex;
						justify-content: center;
						align-items: center;
						flex-direction: column;

						.winnum {
							width: 200rpx;
							margin-top: 10rpx;
							font-size: 180rpx;
							text-align: center;
							color: "#ed2011";
							font-weight: bold;
							-webkit-text-stroke: 1px black;
							font-family: 'NumFont';
						}
					}
				}

				.canvas2 {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
				}

			}

		}
	}


	.resultPopup {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 150rpx;

		.bg {
			background: no-repeat center;
			background-size: cover;
			position: relative;
		}

		.win {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_win_2.png');
			background-size: 500rpx 655rpx;

			.text {
				line-height: 120rpx;
				text-align: center;
				position: absolute;
				width: 100%;
				top: 605rpx;
				left: 0;
				color: #fff;
				font-size: 40rpx;
				font-weight: bolder;
			}
		}

		.loser {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_lose_2.png');
			background-size: 500rpx 605rpx;

			.text {
				line-height: 80rpx;
				text-align: center;
				position: absolute;
				padding: 0 160rpx;
				width: 100%;
				top: 545rpx;
				left: 0;
				color: #fff;
				font-size: 40rpx;
				font-weight: bolder;
			}
		}

		.submitBtn {
			width: 60%;
			margin-top: -120rpx;

			button {
				background: #ee4626;
			}
		}

		.close {
			position: absolute;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			// background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			// border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
			right: 100rpx;
			top: 200rpx;
		}
	}
</style>